﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto.Parameters;

namespace FormsAppToPDF
{
    internal class CreateSign
    {

        public static string certFile = @"D:\files\cret.pfx";
        public static string certPassword = "19970311";
        public static string sourceFile = @"d:\d.pdf";
        public static string releaseFile = @"d:\d_cert.pdf";
        public static string imageFile = @"d:\files\sign.png";
        public static void Sign()
        {
            FileStream stream = File.OpenRead(sourceFile);

            var b = new byte[stream.Length];

            stream.Read(b, 0, b.Length);

            var res = SignPdf(certFile, certPassword, b);
            File.Delete(releaseFile);
            var f = File.OpenWrite(releaseFile);
            f.Write(res, 0, res.Length);
            f.Close();
        }

        public static void Sign(String SourceFile,String ReleaseFile)
        {
            FileStream stream = File.OpenRead(SourceFile);

            var b = new byte[stream.Length];

            stream.Read(b, 0, b.Length);

            var res = SignPdf(certFile, certPassword, b);
            File.Delete(ReleaseFile);
            var f = File.OpenWrite(ReleaseFile);
            f.Write(res, 0, res.Length);
            f.Close();
        }

        public static byte[] SignPdf(string pfxFile, string pfxPass, byte[] input)
        {
            byte[] data = null;

            var store = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open), pfxPass.ToCharArray());
            var alias = "";

            // searching for private key
            foreach (string al in store.Aliases)
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }

            var pk = store.GetKey(alias);

            ICollection<Org.BouncyCastle.X509.X509Certificate> chain = store.GetCertificateChain(alias).Select(c => c.Certificate).ToList();

            var parameters = pk.Key as RsaPrivateCrtKeyParameters;
            using (MemoryStream output = new MemoryStream())
            {
                PdfReader reader = new PdfReader(input);
                // Set the reader (PdfReader) and output (Stream) first
                PdfStamper stamper = PdfStamper.CreateSignature(reader, output, '\0');

                PdfSignatureAppearance signatureAppearance = stamper.SignatureAppearance;

                signatureAppearance.Acro6Layers = false;
                signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC;
                signatureAppearance.Reason = "SCKXJD"; //签名原因
                signatureAppearance.SignDate = DateTime.Now;
                signatureAppearance.LocationCaption = "ShiFang";
                Image img= Image.GetInstance(imageFile);
                signatureAppearance.SignatureGraphic = img;

                //signatureAppearance.SetVisibleSignature("Signature");
                
                signatureAppearance.SetVisibleSignature(
                    new Rectangle(img.Width, img.Height, 300, 150),
                    reader.NumberOfPages,
                    "Signature");
                
                IExternalSignature signature = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);

                MakeSignature.SignDetached(signatureAppearance, signature, chain, null, null, null, 0, CryptoStandard.CMS);

                stamper.Close();
                data = output.ToArray();
            }
            return data;
        }
    }
}
    
